#!/usr/bin/python
#-*- coding:utf-8 -*-

#/remote/企业id/类型id/设备id/upgrade -- 升级命令topic
#{"type":"upgrade","url":"url","sorfVer":""} -- 升级命令msg
#/remote/企业id/类型id/设备id/version -- 设备上报的版本topic
#{"company":企业id,"typeid":类型id,"device_id":设备id,"sorfVer":"","hardVer":""} --设备上报版本msg
#payload : {"type":"update","url":"https://0.0.0.0:0/iotp/go/web/upgrade?file=/LoRaTempHumid_326faf5100000004f02952157a55b36e/WHT2.0.0303.tar.gz","packetType":"ota","softVer":"WHT2.0.0303"}


import paho.mqtt.client as mqtt
import ssl
import json
import time
import random
import threading
from time import sleep
from . import controll

#将控制脚本跑起来，并初始化设备信息
controll = Controll()
controll.devs = devs

#连接配置
user = "d2a7bc0ffd8c0c17adb3028961e03a8a"
pwd = "4bdbebb469c0b00aab0d1195c343f399"
hostip = "10.156.161.41"
port = 58883
#建立连接
client = mqtt.Client()
client.tls_set("ca.crt", certfile=None, keyfile=None,cert_reqs=ssl.CERT_REQUIRED,tls_version=ssl.PROTOCOL_TLSv1_2,ciphers=None) #设置认证文件
client.tls_insecure_set(True)
 #设置用户名、密码
client.username_pw_set(user,pwd)
client.connect(hostip,port,60)
client.on_connect = on_connect
client.on_message = on_message   
client.loop_forever()
 
#设定需要循环的版本，key为上报的版本，value为目标版本
loop={
    "lorawsd":{"version1":'version2',"version2":'version3',"version3":'version1'},
    "ktmb":{"version1":'version2',"version2":'version3',"version3":'version1'},
    "plug":{"version1":'version2',"version2":'version3',"version3":'version1'},    
}

#具体设备状态
devs={
    dev1:{"devtype":"","last_version":"","statu":"","lasttime":"","tar_version":"","push_time":""},
    dev2:{"devtype":"","last_version":"","statu":"","lasttime":"","tar_version":"","push_time":""},
    }


#设备类型信息
typemap = {"lorawsd":"326faf5100000004f02952157a55b36e",  #lora温湿度传感器
"ktmb":"3351be9e00000028741a888be4f9867d",     #空调面板

}   


devmap = {"lorawsd":['sn1','sn2'],
"ktmb":['sn3','sn4']}

urlmap = {"[lorawsd":{"version1":'url1',"version2":'url2',"version3":'url3'},
"ktmb":{"version1":'url1',"version2":'url2',"version3":'url3'},

}

#连接的回调函数
def on_connect(client,userdata,flags,rc):
    print("Connect with result code"+str(rc))
    print("ok")
    #订阅全部设备的版本主题
    sub_all()
  
#接收到消息回调函数
def on_message(client,userdata,msg):
    msg= msg.payload.decode()
    data=json.loads(msg)
    devid=data.device_id
    typeid=data.typeid
    version=data.sorfVer
    devtype=typemap
    tar_version=loop[devtype][version]
    now = time.strftime('%Y-%m-%d %H:%M:%S')
    vertime = now

    #只触发指定的设备类型
    if typeid in idmap:
        print (now+"===设备%s上报版本%s"%(devid,version)) > upgrade.log
        push = controll.push_judge(devid,version,vertime)
        suc = controll.suc_judge(devid,version,vertime)
        controll.devs[devtype][lasttime] = vertime
        controll.devs[devtype][last_version] = version
        url=urlmap[devtype][version]
        #上报时间差小于15分钟时，判断是否是升级成功
        while push == False:
            if suc == True:
                pub_upgrade(devid,typeid,tar_version,client,url)
                
            #小于15分钟并且不是升级成功的情况，忽略本次上报
            elif:
                break
        #上报时间差大于15分钟时，执行本次推送
        while push == True:
                pub_upgrade(devid,typeid,tar_version,client,url)
                
    elif :
        break

#发布消息的回调函数
def on_publish(msg,rc):
    if rc==0:
        print("publish msg:"+msg)
    else:
        print("error when publish msg:"+msg)

#订阅全部类型设备主题
def sub_all():
    for atype in typemap:
        for dev_id in range(len(devmap[atype]))
            client.subscribe("/remote/asqwerty0000001d3625bafa0da9ea/%s/%s/version"%(atype,dev_id),2)



#发布升级命令主题    
def pub_upgrade(devid,typeid,version,client,url):
        topic='/remote/asqwerty0000001d3625bafa0da9ea/%s/%s/upgrade'%(typeid,devid)
        msg = '{"type":"upgrade","url":%s,"sorfVer":""}'%(url)
        now = time.strftime('%Y-%m-%d %H:%M:%S')
        print(now+"===发送命令：设备%s升级到版本%s"%(devid,version)) > upgrade.log
        client.publish(topic,payload=msg,qos=2,retain=False)


       
